import { Store, StoreHandler, useIsomorphicLayoutEffect } from "../../core";

import StoreProps from "./StoreProps";
import { useState } from "react";

const useCurrentPage = (store: Store<StoreProps>): { currentPage: number } => {
  const [currentPage, setCurrentPage] = useState(store.get("currentPage") || 0);

  const handleCurrentPageChanged: StoreHandler<number> = (
    currentPageIndex: number
  ) => {
    setCurrentPage(currentPageIndex);
  };

  useIsomorphicLayoutEffect(() => {
    store.subscribe("currentPage", handleCurrentPageChanged);

    return () => {
      store.unsubscribe("currentPage", handleCurrentPageChanged);
    };
  }, []);

  return { currentPage };
};

export default useCurrentPage;
